var prefix = jsctx + "/marketActivity";

var rechargeDiscount = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageRechargeDiscount",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    cache: false,
                    pageSize: 20,
                    pageList: [10, 20, 30],
                    pageNumber: 1,
                    sidePagination: "server",
                    paginationShowPageGo: true,
                    height: h,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            startTime: $("#startTime").val().trim(),
                            endTime: $("#endTime").val().trim()
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'activityName', title: '充值活动名称', align: 'left', width: '150'},
                        {
                            field: 'sendType', title: '活动对象',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '2') {
                                    return '普通用户'
                                } else if (value == '3') {
                                    return '企业用户'
                                } else if (value == '4') {
                                    return '全部'
                                }
                            }
                        },
                        {field: 'paymentMethod', title: '参与的支付方式', align: 'left', width: '100'},
                        {field: 'clientIsSupported', title: '客户端支持', align: 'left', width: '110'},
                        {
                            field: '', title: '活动时间',
                            width: '300', align: 'center',
                            formatter: function (value, row, index) {
                                return row.beginTime + '~' + row.endTime
                            }
                        },
                        {field: 'lastUpdatedTime', title: '最后编辑时间', align: 'left', width: '170'},
                        {field: 'createdTime', title: '创建时间', align: 'left', width: '170'},
                        {
                            field: 'rewardType', title: '活动类型',
                            width: '120', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '2') {
                                    return '充值送优惠券'
                                } else if (value == '4') {
                                    return '充值减免'
                                }
                                // else if (value == '5') {
                                //     return '充值送优惠券/充值减免'
                                // }
                            }
                        },
                        {
                            field: 'statusString', title: '状态', width: '120', align: 'center'
                        },
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '250 ', align: 'center',
                            formatter: function (value, row, index) {


                                var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="查看详情" onclick="rechargeDiscount.detailRechargeDiscount(\''
                                    + row.marketActivityId
                                    + '\')">查看详情</a> ';

                                var b = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" title="编辑" onclick="rechargeDiscount.editRechargeDiscount(\''
                                    + row.marketActivityId
                                    + '\')">编辑</a> ';

                                if (row.status == '0') {
                                    var c = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="启动" onclick="rechargeDiscount.updateStatusForStart(\''
                                        + row.marketActivityId
                                        + '\')">启动</a> ';
                                } else if (row.status == '1') {
                                    var c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="停用" onclick="rechargeDiscount.updateStatusForStop(\''
                                        + row.marketActivityId
                                        + '\')">停用</a> ';
                                }

                                if (row.statusString == '已结束') {
                                    return a + c;
                                } else if (row.statusString == '停用') {
                                    return a + c;
                                } else {
                                    return a + b + c;
                                }

                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addRechargeDiscount() {
        location.href = prefix + "/addRechargeDiscount";
        // $.ajax({
        //     url: prefix + "/isExecuteDiscount",
        //     type: "get",
        //     success: function (data) {
        //         if (data.status == 200) {
        //             location.href = prefix + "/addRechargeDiscount";
        //         } else {
        //             layer.msg(data.message);
        //         }
        //     }
        // });
    }

    function editRechargeDiscount(marketActivityId) {
        location.href = prefix + "/editRechargeDiscount/" + marketActivityId;
    }

    function detailRechargeDiscount(marketActivityId) {
        location.href = prefix + "/detailRechargeDiscount/" + marketActivityId;
    }


    function updateStatusForStart(marketActivityId) {
        layer.confirm('确定要启动选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'marketActivityId': marketActivityId,
                    'status': '1'
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("启动成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function updateStatusForStop(marketActivityId) {
        layer.confirm('确定要停用选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'marketActivityId': marketActivityId,
                    'status': '0'
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("停用成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    //新增优惠项
    function addList() {
        if ($("input[name='rewardType']:checked").val() == "2") {
            var couponHtml = $(".couponHtml").html();
            var str = "<div class='layui-card-body coupon-layui-card-body col-sm-10 row'>" +
                "<div class='layui-form-mid layui-word-aux'>" + "满" + "</div>" +
                "<div class='col-sm-3'>" +
                "<input class='form-control requireAmount' min='0' type='number' onkeyup='num(this)'>" +
                "</div>" +
                "<div class='layui-form-mid layui-word-aux'>" + "赠送" + "</div>" +
                "<div class='col-sm-2'>" +
                "<input class='form-control sendCount' min='1' type='number' oninput=\"this.value = this.value.replace(/[^0-9]/g, '')\">" +
                "</div>" +
                "<div class='layui-form-mid layui-word-aux'>" + "张" + "</div>" +
                "<div class='col-sm-1 layui-form-mid layui-word-aux'>" + "</div>" +
                "<div class='col-sm-5'>" +
                "<select class='form-control ticketTypeId' id='ticketTypeId'>" + couponHtml
                +
                "</select>" +
                "</div>" +
                "<a class='btn btn-danger  btn-sm del_btn delList'>删除</a>" +
                "</div>"
            $(".coupon-layui-card").append(str);
            layui.use('form', function () {  //此段代码必不可少
                var form = layui.form;
                form.render();
            });
        } else if ($("input[name='rewardType']:checked").val() == "4") {
            var str = "<div class='layui-card-body cash-layui-card-body col-sm-6 row'>" +
                "<div class='layui-form-mid layui-word-aux'>" + "满" + "</div>" +
                "<div class='col-sm-6'>" +
                "<input class='form-control requireAmount' min='0' type='number' onkeyup='num(this)'>" +
                "</div>" +
                "<div class='layui-form-mid layui-word-aux'>" + "减" + "</div>" +
                "<div class='col-sm-4'>" +
                "<input class='form-control sendAmount' min='1'  type='number' oninput=\"this.value = this.value.replace(/[^0-9]/g, '')\">" +
                "</div>" +
                "<div class='layui-form-mid layui-word-aux'>" + "元" + "</div>" +
                "<a class='btn btn-danger  btn-sm del_btn delList'>" + "删除" + "</a>" +
                "</div>"

            $(".cash-layui-card").append(str);
        }
    }

    //删除优惠项
    $(function () {
        $(".layui-card").on("click", ".delList", function () {
            $(this).parents(".layui-card-body").remove()
        })
    })


    function goBack() {
        window.history.back();
    }


    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addRechargeDiscount: addRechargeDiscount,
        detailRechargeDiscount: detailRechargeDiscount,
        editRechargeDiscount: editRechargeDiscount,
        updateStatusForStart: updateStatusForStart,
        updateStatusForStop: updateStatusForStop,
        addList: addList,
        // deleteBanner: deleteBanner,
        // editBanner: editBanner,
    };
})();


var addRechargeDiscount = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            var ticketList = [];
            var required = true;
            if ($("input[name='rewardType']:checked").val() == "2") {//优惠券
                $(".coupon-layui-card-body").each(function () {
                    var ticketListObj = {};
                    var requireAmount = $(this).find(".requireAmount").val();
                    var sendCount = $(this).find(".sendCount").val();
                    var ticketTypeId = $(this).find(".ticketTypeId").val();

                    if (requireAmount == '' || requireAmount == null) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入满足金额" + "</label>"
                        $(this).find(".requireAmount").after(str)
                        required = false
                    } else if (requireAmount < 1) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入不小于 1 的数值" + "</label>"
                        $(this).find(".requireAmount").after(str)
                        required = false
                    } else {
                        ticketListObj.requireAmount = requireAmount
                    }
                    if (sendCount == '' || sendCount == null) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入赠送张数" + "</label>"
                        $(this).find(".sendCount").after(str)
                        required = false
                    } else if (sendCount < 1) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入不小于 1 的数值" + "</label>"
                        $(this).find(".sendCount").after(str)
                        required = false
                    } else {
                        ticketListObj.sendCount = sendCount;
                    }
                    ticketListObj.ticketTypeId = ticketTypeId;
                    ticketList.push(ticketListObj)
                })
            } else if ($("input[name='rewardType']:checked").val() == "4") {//现金
                $(".cash-layui-card-body").each(function () {
                    var ticketListObj = {};
                    var requireAmount = $(this).find(".requireAmount").val();
                    var sendAmount = $(this).find(".sendAmount").val();

                    if (requireAmount == '' || requireAmount == null) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入满足金额" + "</label>"
                        $(this).find(".requireAmount").after(str)
                        required = false
                    } else if (requireAmount < 1) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入不小于 1 的数值" + "</label>"
                        $(this).find(".requireAmount").after(str)
                        required = false
                    } else {
                        ticketListObj.requireAmount = requireAmount
                    }
                    if (sendAmount == '' || sendAmount == null) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入减免金额" + "</label>"
                        $(this).find(".sendAmount").after(str)
                        required = false
                    } else if (sendAmount < 1) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "请输入不小于 1 的数值" + "</label>"
                        $(this).find(".sendAmount").after(str)
                        required = false
                    } else {
                        ticketListObj.sendAmount = sendAmount
                    }
                    if (sendAmount >= requireAmount) {
                        var str = "<label class='error' >" + "<i class='fa fa-times-circle'>" + "</i>" + "减免金额要小于满减金额" + "</label>"
                        $(this).find(".sendAmount").after(str)
                        required = false
                    }

                    ticketList.push(ticketListObj)
                })
            }

            if (!required) {
                return;
            }

            var formData = new FormData($("#frmRechargeDiscount")[0]);
            formData.append("ticketList", JSON.stringify(ticketList));
            formData.append("marketActivityId", $("#marketActivityId").val() ? $("#marketActivityId").val() : '');
            // if ($("input[name='sendTicket']").is(":checked") && $("input[name='reduction']").is(":checked")) {
            //     formData.append("rewardType", 5);
            // } else if ($("input[name='sendTicket']").is(":checked") && !$("input[name='reduction']").is(":checked")) {
            //     formData.append("rewardType", 2);
            // } else if (!$("input[name='sendTicket']").is(":checked") && $("input[name='reduction']").is(":checked")) {
            //     formData.append("rewardType", 4);
            // }
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateRechargeDiscount",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    isajaxsend = true
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = true
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true
                        parent.layer.alert(data.message)
                    }

                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmRechargeDiscount").validate({
            rules: {
                activityName: {
                    required: true,
                    maxlength: 20
                },
                maxDiscountCount: {
                    required: true,
                    min: 0,
                    maxlength: 9
                },
                beginTime: {
                    required: true,
                },
                endTime: {
                    required: true,
                },
                remark: {
                    maxlength: 500,
                    required: true
                },
            },
            messages: {
                activityName: {
                    required: icon + "请输入活动名称",
                    maxlength: icon + "活动名称字数限制为20"
                },
                maxDiscountCount: {
                    required: icon + "请输入同个用户最多享受优惠次数",
                    min: icon + "请输入大于0的数",
                    maxlength: icon + "最大长度不超过9位"
                }
                ,
                beginTime: {
                    required: icon + "请选择开始时间",
                },
                endTime: {
                    required: icon + "请选择结束时间",
                },
                remark: {
                    required: icon + "请输入活动规则",
                    maxlength: icon + "活动规则描述字数限制为500"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();
